package com.qingzhuge.common.jwt;

import com.google.gson.Gson;
import com.qingzhuge.common.utils.TimeUtil;
import io.jsonwebtoken.*;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

/**
 * @author : zero.xiao
 * @description :
 * @date :2018/8/8 0008 上午 9:45
 * @since : 1.0.0
 * @modified :
 */
public class JwtTokenUtil {
    private static final String MD5 = "MD5";

    private static Key createKey(){
        SignatureAlgorithm saa=SignatureAlgorithm.HS256;
        byte[] bin=DatatypeConverter.parseBase64Binary("f3973b64918e4324ad85acea1b6cbec5");
        return new SecretKeySpec(bin,saa.getJcaName());
    }

    public static String createToken(Map<String,Object> payLoad){
        JwtBuilder builder = Jwts.builder();
        LocalDateTime now = LocalDateTime.now();
        builder.setIssuedAt(TimeUtil.localDateTime2Date(now));
        builder.setIssuer("token-server");
        builder.setExpiration(TimeUtil.localDateTime2Date(now));
        return builder.setPayload(new Gson().toJson(payLoad))
        .signWith(SignatureAlgorithm.HS256, createKey()).compact();
    }

    public static String createToken(Long period,Map<String,Object> payLoad){
        JwtBuilder builder = Jwts.builder();
        builder.setIssuer("token-server");
        // 当前时间戳
        Long currentTimeMillis = System.currentTimeMillis();
        // 设置签发时间
        builder.setIssuedAt(new Date(currentTimeMillis));
        // 设置到期时间
        if (null != period) {
            period = (period >> 1) * 1000;
            Date expiration = new Date(currentTimeMillis + period);
            builder.setExpiration(expiration);
        }
        // 压缩，可选GZIP
        builder.compressWith(CompressionCodecs.DEFLATE);
        // 加密设置
        builder.signWith(SignatureAlgorithm.HS256, createKey());
        builder.setPayload(new Gson().toJson(payLoad));
        return builder.compact();
    }


    public static Claims phaseToken(String token){
        Jws<Claims> claimsJwt=Jwts.parser().setSigningKey(createKey()).parseClaimsJws(token);
        return claimsJwt.getBody();
    }

    public static String getMd5KeyFromToken(String token) {
        Claims claims = phaseToken(token);
        return claims.get(MD5, String.class);
    }
}
